"""
智能客服业务助理 FastAPI 后端服务
提供聊天、OCR、语音识别等 API 接口
"""

import os
import json
import time
import base64
import logging
from typing import Optional
from contextlib import asynccontextmanager

from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse

from agents.planner import get_customer_service_agent
from services.llm_service import create_llm_service
from services.azure_ocr import ocr_image
from utils.logger import init_logging, log_api_request, log_agent_action, log_error

# 初始化日志
init_logging()
logger = logging.getLogger(__name__)

# 全局变量
agent = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    global agent

    # 启动时初始化
    logger.info("Starting AI Customer Service Backend")

    try:
        # 初始化语言模型和 Agent
        llm = create_llm_service()
        agent = get_customer_service_agent(llm)
        logger.info(f"Agent initialized successfully with {llm._llm_type} service")
    except Exception as e:
        logger.error(f"Failed to initialize agent: {e}")
        # 创建一个简单的后备处理函数
        agent = None

    yield

    # 关闭时清理
    logger.info("Shutting down AI Customer Service Backend")


# 创建 FastAPI 应用
app = FastAPI(
    title="AI Customer Service Demo",
    description="智能客服业务助理 API 服务",
    version="1.0.0",
    lifespan=lifespan
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该指定具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    """根路径"""
    return {"message": "AI Customer Service Backend is running", "version": "1.0.0"}


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "timestamp": time.time()}


@app.post("/chat")
async def chat(
    message: str = Form(...),
    image: Optional[UploadFile] = File(None)
):
    """
    聊天接口 - 处理用户消息

    Args:
        message: 用户消息
        image: 可选的图片文件

    Returns:
        JSON 响应包含思考过程、动作、观察和答案
    """
    start_time = time.time()

    try:
        if not agent:
            raise HTTPException(status_code=503, detail="Agent not initialized")

        # 处理图片输入
        context = {}
        if image:
            try:
                # 读取图片数据
                content = await image.read()
                image_b64 = base64.b64encode(content).decode()

                # 调用 OCR 服务
                ocr_result = await ocr_image(image_b64)

                if ocr_result.get("success"):
                    context["ocr_result"] = ocr_result
                    logger.info(f"OCR successful: order_id={ocr_result.get('order_id')}")
                else:
                    logger.warning(f"OCR failed: {ocr_result.get('error')}")

            except Exception as e:
                logger.error(f"Image processing failed: {e}")
                context["ocr_error"] = str(e)

        # 调用 Agent 处理请求
        response = await agent.aprocess_request(message, context)

        # 记录日志
        log_agent_action("chat", message, response)

        # 计算处理时间
        duration = time.time() - start_time
        log_api_request("/chat", "POST", 200, duration)

        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "data": response,
                "processing_time": f"{duration:.2f}s"
            }
        )

    except Exception as e:
        duration = time.time() - start_time
        log_error("chat_error", str(e), message=message, duration=duration)
        log_api_request("/chat", "POST", 500, duration)

        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e),
                "data": {
                    "thought": "处理请求时发生错误",
                    "action": "",
                    "observation": f"错误: {str(e)}",
                    "answer": "抱歉，处理您的请求时出现问题。请稍后重试。",
                    "success": False
                }
            }
        )


@app.post("/ocr")
async def process_ocr(file: UploadFile = File(...)):
    """
    OCR 图片识别接口

    Args:
        file: 上传的图片文件

    Returns:
        OCR 识别结果
    """
    start_time = time.time()

    try:
        # 读取图片数据
        content = await file.read()
        image_b64 = base64.b64encode(content).decode()

        # 调用 OCR 服务
        result = await ocr_image(image_b64)

        duration = time.time() - start_time
        log_api_request("/ocr", "POST", 200, duration)

        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "data": result,
                "processing_time": f"{duration:.2f}s"
            }
        )

    except Exception as e:
        duration = time.time() - start_time
        log_error("ocr_error", str(e))
        log_api_request("/ocr", "POST", 500, duration)

        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e),
                "data": {
                    "success": False,
                    "amount": "0.00",
                    "order_id": "UNKNOWN",
                    "date": "UNKNOWN"
                }
            }
        )


@app.post("/asr")
async def process_asr(audio: UploadFile = File(...)):
    """
    语音转文字接口

    Args:
        audio: 上传的音频文件

    Returns:
        语音识别结果
    """
    start_time = time.time()

    try:
        # 这里应该集成语音识别服务
        # 暂时返回模拟结果
        content = await audio.read()

        # 模拟语音识别处理
        mock_text = "请帮我查询订单状态"  # 模拟识别结果

        duration = time.time() - start_time
        log_api_request("/asr", "POST", 200, duration)

        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "data": {
                    "text": mock_text,
                    "confidence": 0.95,
                    "language": "zh-CN"
                },
                "processing_time": f"{duration:.2f}s"
            }
        )

    except Exception as e:
        duration = time.time() - start_time
        log_error("asr_error", str(e))
        log_api_request("/asr", "POST", 500, duration)

        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e),
                "data": {
                    "text": "",
                    "confidence": 0.0
                }
            }
        )


@app.get("/logs")
async def get_logs(lines: int = 100):
    """
    获取最近的日志记录

    Args:
        lines: 返回的日志行数

    Returns:
        日志记录列表
    """
    try:
        # 这里应该从日志文件中读取最近的记录
        # 暂时返回模拟数据
        mock_logs = [
            {
                "timestamp": time.time(),
                "level": "INFO",
                "message": "Agent processed chat request",
                "user": "demo_user"
            }
        ]

        return JSONResponse(
            status_code=200,
            content={
                "success": True,
                "data": mock_logs[:lines]
            }
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e)
            }
        )


if __name__ == "__main__":
    import uvicorn

    # 开发环境运行
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )
